package com.example.app.service.impl;

import com.example.app.domain.bo.UserBO;
import com.example.app.domain.dto.UserDTO;
import com.example.app.domain.vo.UserVO;
import com.example.app.service.LoginService;
import com.example.app.utils.JwtUtil;
import com.example.app.utils.RedisCache;
import com.example.app.utils.Result;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    private final RedisCache redisCache;

    public LoginServiceImpl(
            AuthenticationManager authenticationManager,
            RedisCache redisCache
    ) {
        this.authenticationManager = authenticationManager;
        this.redisCache = redisCache;
    }

    @Override
    public Result<UserVO> login(UserDTO userDTO) {
        // 用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDTO.getPhone(), userDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 认证不通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        // 认证通过，生成JWT，存入Result返回
        UserBO userBO = (UserBO) authenticate.getPrincipal();
        Integer id = userBO.getId();
        String userId = id.toString();
        // 生成载荷
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userId);
        // 编码JWT
        String jwt = JwtUtil.generateJwt(claims);
        Map<String, String> token = new HashMap<>();
        token.put("token", jwt);

        // TODO 获取用户信息

        // TODO 判断用户角色

        // 创建用于返回前端的VO类
        UserVO userVO = null;

        // TODO 处理VO数据

        // 完整的用户信息存入Redis
        redisCache.setCacheObject("login:" + userId, userBO);

        if (userVO == null) {
            throw new RuntimeException("用户信息错误");
        }

        return Result.success("登录成功", userVO);
    }
}
